package com.example.ykprinteridcard;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.yanke.idcard.IDCardResultListener;
import com.example.yanke.idcard.YKIDCardManager;
import com.google.gson.Gson;
import com.telpo.tps550.api.TelpoException;
import com.telpo.tps550.api.idcard.IdCard;
import com.telpo.tps550.api.idcard.IdentityMsg;

public class MainActivity extends AppCompatActivity {

    private YKIDCardManager mYKIDCardManager;
    private TextView tvText;
    private ImageView ivHead;
    private Bitmap bitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvText = findViewById(R.id.tvText);
        ivHead = findViewById(R.id.ivHead);
        mYKIDCardManager = new YKIDCardManager(this, new IDCardResultListener() {
            @Override
            public void result(IdCard mIdCard, IdentityMsg info) {
                try {
                    byte[] image = mIdCard.getIdCardImageOverseas(info);
                    if (image.length == 2048 || image.length == 1024) {
                        bitmap = mIdCard.decodeIdCardImageOverseas(image);
                    }
                    tvText.setText(
                            getString(R.string.idcard_xm) + info.getName() + "\n\n" + getString(R.string.idcard_xb)
                                    + info.getSex() + "\n\n" + getString(R.string.idcard_csrq) + info.getBorn() + "\n\n"
                                    + getString(R.string.idcard_country) + getString(R.string.idcard_yxqx)
                                    + info.getPeriod() + "\n\n" + getString(R.string.idcard_qzjg) + info.getApartment()
                                    + "\n\n" + getString(R.string.idcard_sfhm) + info.getNo() + "\n\n");
                    ivHead.setImageBitmap(bitmap);
                    info.setHead_photo(null);//不打印头像流
                    Log.d("身份证信息", new Gson().toJson(info));
                } catch (TelpoException e) {
                    e.printStackTrace();
                }
            }

        });
    }

    public void readIDCardSingle(View view) {
        mYKIDCardManager.readInfo();
    }

    public void btReadIDCard(View view) {
        if (mYKIDCardManager != null)
            mYKIDCardManager.readLoop();
    }

    public void btStopIDCard(View view) {
        if (mYKIDCardManager != null)
            mYKIDCardManager.stopReadThread();
    }

    public void toPrinter(View view) {
        startActivity(new Intent(this,PrinterActivity.class));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mYKIDCardManager != null)
            mYKIDCardManager.releaseIDCard();
    }

}